import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_app/app/models/movie.dart';
import '/config/decoders.dart';
import 'package:nylo_framework/nylo_framework.dart';

class SearchMovieApiService extends NyApiService {
  SearchMovieApiService({BuildContext? buildContext})
      : super(buildContext, decoders: modelDecoders);

  @override
  String get baseUrl => getEnv('API_BASE_URL');

  Future<Movies> searchMovie(String url, keyword, int page) async {
    return await network(
        request: (request) => request.get(
              "$url/api.php/provide/vod/",
              queryParameters: {'ac': 'videolist', 'wd': keyword, 'pg': page},
            ),
        headers: {
          'User-Agent':
              'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
          'Accept': 'application/json'
        },
        handleFailure: (dioError) {
          print('API request failed: $dioError');
          return Movies();
        },
        handleSuccess: (Response response) {
          // response - Dio Response object
          NyLogger.info('API abgresponse: $response');

          try {
            dynamic data = response.data;
            if (data is String) {
              data = jsonDecode(data);
            }
            return Movies.fromJson(data);
          } catch (e) {
            print('Failed to parse API response: $e');
            return Movies();
          }
        });
  }
}
